﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using XLua;
using XLua.LuaDLL;


/// <summary>
/// Lua管理器
/// </summary>
public class LuaManager : MonoBehaviour
{
    public static LuaManager _instance;

    private LuaEnv LuaEvn = new LuaEnv();

    private void Awake()
    {
        _instance = this;
        RegistAssetFolder();
    }

    /// <summary>
    /// 
    /// </summary>
    public void RegistAssetFolder()
    {
        //Xlua通过此函数可以在sreamingAssets下加载Lua代码(自定义方式)
        LuaEvn.AddLoader(customLoader);
    }

    /// <summary>
    /// todo 通过此函数执行lua代码
    /// </summary>
    /// <param name="chunk"></param>
    /// <param name="chunkName"></param>
    /// <param name="evn"></param>
    public void DoString(string chunk,string chunkName = "chunk",LuaTable evn = null)
    {
        LuaEvn.DoString(chunk, chunkName, evn);
    }

    /// <summary>
    /// 调用lua方法
    /// </summary>
    public object[] CallLuaFunction(string luaName,string methodName,params object[] args)
    {
        //反射获取对象和函数
        LuaTable table = LuaEvn.Global.Get<LuaTable>(luaName);
        LuaFunction function = table.Get<LuaFunction>(methodName);
        return function.Call(args);
    }

    Dictionary<string,byte[]> dic = new Dictionary<string, byte[]>();

    private byte[] customLoader(ref string fileName)
    {
        print("获取lua脚本1");
        //获取lua文件所在目录
        string luaPath = PathUtil.GetAssetBundleOutPath() + "/Lua";
        print("获取lua脚本2");
        return precessDir(new DirectoryInfo(luaPath), fileName);
    }

    private byte[] precessDir(FileSystemInfo fileSystemInfo,string fileName)
    {
        //获取路径类型对象
        DirectoryInfo directoryInfo = fileSystemInfo as DirectoryInfo;
        //获取路径下的全部对象(包括文件夹)
        FileSystemInfo[] files = directoryInfo.GetFileSystemInfos();
        //遍历文件夹下的全部对象(包括文件夹)
        foreach (var item in files)
        {
            FileInfo file = item as FileInfo;
            if (file == null)
            {
                //如果转换不成功，则该对象是文件夹，遍历该文件夹
                precessDir(item, fileName);
            }
            else
            {
                //转换成功，获取文件名
                string tempName = item.Name.Split('.')[0];
                //判断是否是meta文件或者文件名不是我们指定的文件，无视该文件
                if (item.Extension == ".meta"||tempName != fileName)
                {
                    continue;
                }
                byte[] bytes = File.ReadAllBytes(file.FullName);
                dic.Add(fileName,bytes);
                return bytes;
            }
        }
        return null;
    }

}
